package com.nbsaas.lbs.baidu.geo;

import java.io.IOException;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.nbsaas.http.Connection;
import com.nbsaas.http.HttpConnection;
import com.nbsaas.http.Connection.Method;

public class TencentGeoUtils {

	private static String nearbyurl = "http://apis.map.qq.com/ws/geocoder/v1";
	private static String ak = "EDMBZ-QHRH4-RZ3UC-X425Z-AAH7J-BMBOY";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String value = "34.27779990,108.95309828";
		LbsAddress lbs = get(value);
		System.out.println(lbs);

	}

	private static LbsAddress get(String value) {
		LbsAddress lbs=new LbsAddress();
		Connection connection = HttpConnection.connect(nearbyurl);
		connection.data("key", ak);
		connection.data("location", value);
		connection.data("get_poi", "0");
		connection.data("output", "json");
		connection.method(Method.GET);
		String msg = null;
		try {
			msg = connection.execute().body();
			JsonParser jsonParser = new JsonParser();
			JsonObject resp =jsonParser.parse(msg).getAsJsonObject();
			JsonElement result = resp.get("result");
			if (result!=null&&result.isJsonObject()) {
				JsonObject r = result.getAsJsonObject();
				JsonObject address_component = r.get("address_component")
						.getAsJsonObject();
				
				lbs.setNation(getkey(address_component, "nation"));
				lbs.setProvince(getkey(address_component, "province"));
				lbs.setCity(getkey(address_component, "city"));
				lbs.setDistrict(getkey(address_component, "district"));
				lbs.setStreet(getkey(address_component, "street"));
				lbs.setStreet_number(getkey(address_component, "street_number"));

			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lbs;
	}

	private static String getkey(JsonObject address_component, String key) {
		String result = "";
		try {
			result = address_component.getAsJsonObject().get(key).getAsString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
